package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CurrencyFacade;
import ar.com.ford.it.fullEconomics.facade.RequestFacade;
import ar.com.ford.it.fullEconomics.facade.SupplyFacade;
import ar.com.ford.it.fullEconomics.facade.VehiclelinFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas012VehicleVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr01Request;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr02Requestitm;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.view.form.RequestDetailForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class RequestDetailAction extends AbstractBaseAction {

    private Collection getStatusCombo(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("P", resources
                .getMessage("request.label.pending")));
        list.add(new OptionCombo("R", resources
                .getMessage("request.label.rejected")));
        list.add(new OptionCombo("I", resources
                .getMessage("request.label.inProcess")));
        list.add(new OptionCombo("C", resources
                .getMessage("request.label.closed")));

        return list;
    }

    /**
     * inicializa la pantalla, recibe un recuesta, busca sus items y los
     * desplega en el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        RequestDetailForm form = (RequestDetailForm) actionForm;
        form.resetForm();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        CurrencyFacade currencyFacade = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        VehiclelinFacade vehicleLineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);

        Teesr01Request req = (Teesr01Request) request
                .getAttribute("requestSelected");
        form.setRequest(req);
        form.setOperation("newRequest");
        form.setComments(req.getEesr01RequestCommentsX());
        try {
            request.getSession().setAttribute(
                    "commColl",
                    commodityFacade.findCommodities("", "", user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("partClassColl",
                    commodityFacade.getPartClases());
            request.getSession().setAttribute("currColl",
                    currencyFacade.getAllCurrency());
            request.getSession().setAttribute("lineColl",
                    vehicleLineFacade.findAllVehiclelin());
            request.getSession().setAttribute("statusColl",
                    this.getStatusCombo(request));
            form.setItems(requestFacade.findRequestItems(req));

        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * setea el item para ser editado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editRequestItem(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {

        RequestDetailForm form = (RequestDetailForm) actionForm;
        form.setItemMapped();
        form.setItemForEdit(form.getItemSelected());
        return mapping.findForward("success");
    }

    /**
     * Elimina el item seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteRequestItem(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        RequestDetailForm form = (RequestDetailForm) actionForm;
        form.setItemMapped();
        RequestFacade facade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);

        try {
            facade.deleteRequestItem(form.getItemSelected());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        request.setAttribute("requestSelected", form.getRequest());
        return mapping.findForward("success");
    }

    /**
     * crea o actualiza un item
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward saveRequestItem(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        RequestDetailForm form = (RequestDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);
        CommodityFacade commodityfacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        SupplyFacade supplyFacade = (SupplyFacade) FacadeProvider.getFacade(
                request, SupplyFacade.class);
        VehiclelinFacade lineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);

        Teesr02Requestitm requestItem = null;
        try {
            if (form.getSection().equalsIgnoreCase("create")) {
                requestItem = form.getRequestItemForCreate();
                if (form.getRequestScope().equalsIgnoreCase("part")) {
                    Teesp01Part part = new Teesp01Part();
                    part.setEesp01PartClassCodeC(form.getPartClass());
                    part.setEesp01PartPrefixCodeC(form.getPrefix());
                    part.setEesp01PartBaseCodeC(form.getBase());
                    part.setEesp01PartSuffixCodeC(form.getSuffix());
                    Teesp04Supply supply = new Teesp04Supply();
                    supply.setTeesp01Part(part);
                    supply.setTeess01Supplier(requestItem.getTeesr01Request()
                            .getTeess01Supplier());
                    supply.setEesp04PlantCodeC(user.getTeesg01Plant());
                    supply = supplyFacade.getSupplyByPk(supply);
                    if (supply == null) {
                        throw new FullEconomicsException(new Exception(),
                                "requestItem.error.invalidSupply");
                    }
                    requestItem.setTeesp04Supply(supply);
                    requestItem.setEesr02ReqitmTypeCodeC("P");
                } else if (form.getRequestScope().equalsIgnoreCase("commodity")) {
                    Teesp02Commodity commodity = commodityfacade
                            .findCommodityByCode(form.getCommodity(), user
                                    .getTeesg01Plant());
                    requestItem.setTeesp02Commodity(commodity);
                    requestItem.setEesr02ReqitmTypeCodeC("C");
                } else {
                    requestItem.setEesr02ReqitmTypeCodeC("A");
                }
                if (!form.getVehicleLine().equalsIgnoreCase("-1")) {
                	Ncas012VehicleVw line = new Ncas012VehicleVw();
                    line.setCas012VehicleCodeC(form.getVehicleLine());
                    requestItem.setNcas012VehicleVw(lineFacade
                            .findVehicleLineByPk(line));
                }
                requestFacade.createRequestItem(requestItem, user);
            } else {
                requestItem = form.getRequestItemForUpdate();
                if (form.getRequestScope().equalsIgnoreCase("part")) {
                    Teesp01Part part = new Teesp01Part();
                    part.setEesp01PartClassCodeC(form.getPartClass());
                    part.setEesp01PartPrefixCodeC(form.getPrefix());
                    part.setEesp01PartBaseCodeC(form.getBase());
                    part.setEesp01PartSuffixCodeC(form.getSuffix());
                    Teesp04Supply supply = new Teesp04Supply();
                    supply.setTeesp01Part(part);
                    supply.setTeess01Supplier(requestItem.getTeesr01Request()
                            .getTeess01Supplier());
                    supply.setEesp04PlantCodeC(user.getTeesg01Plant());
                    supply = supplyFacade.getSupplyByPk(supply);
                    if (supply == null) {
                        throw new FullEconomicsException(new Exception(),
                                "requestItem.error.invalidSupply");
                    }
                    requestItem.setTeesp04Supply(supply);
                    requestItem.setEesr02ReqitmTypeCodeC("P");
                } else if (form.getRequestScope().equalsIgnoreCase("commodity")) {
                    Teesp02Commodity commodity = commodityfacade
                            .findCommodityByCode(form.getCommodity(), user
                                    .getTeesg01Plant());
                    requestItem.setTeesp02Commodity(commodity);
                    requestItem.setEesr02ReqitmTypeCodeC("C");
                } else {
                    requestItem.setEesr02ReqitmTypeCodeC("A");
                }
                if (!form.getVehicleLine().equalsIgnoreCase("-1")) {
                	Ncas012VehicleVw line = new Ncas012VehicleVw();
                    line.setCas012VehicleCodeC(form.getVehicleLine());
                    requestItem.setNcas012VehicleVw(lineFacade
                            .findVehicleLineByPk(line));
                }
                requestFacade.updateRequestItem(requestItem, user);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        request
                .setAttribute("requestSelected", requestItem
                        .getTeesr01Request());
        return mapping.findForward("success");
    }

    /**
     * guarda los comentarios en el request
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward saveComments(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        RequestDetailForm form = (RequestDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);

        try {
            form.getRequest().setEesr01RequestCommentsX(form.getComments());
            requestFacade.updateRequest(form.getRequest(), user);

        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        request.setAttribute("requestSelected", form.getRequest());
        return mapping.findForward("success");
    }

    /**
     * guarda los comentarios en el request
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward closeRequest(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        RequestDetailForm form = (RequestDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);

        Teesr01Request req = form.getRequest();
        try {
            requestFacade.closeRequest(req.getEesr01RequestNumberK(), user);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        req.setEesr01RequestStatusCodeC("C");
        request.setAttribute("requestSelected", request);

        return mapping.findForward("success");
    }

    /**
     * guarda los comentarios en el request
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward reopenRequest(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        RequestDetailForm form = (RequestDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        RequestFacade requestFacade = (RequestFacade) FacadeProvider.getFacade(
                request, RequestFacade.class);
        Teesr01Request req = form.getRequest();
        try {
            requestFacade.reopenRequest(req.getEesr01RequestNumberK(), user);

        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        req.setEesr01RequestStatusCodeC("I");
        request.setAttribute("requestSelected", req);
        return mapping.findForward("success");
    }

}
